<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">在线门诊管理后台</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="loginForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" prefix-icon="el-icon-user" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock" />
        </el-form-item>
        <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import {setToken, setUser} from '@/utils/auth';
import {adminLogin} from "@/api/admin.js";

const router = useRouter();
const form = reactive({
  username: '',
  password: '',
});
const loginForm = ref(null);

const user = ref({});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' },
  ],
};

const handleLogin = () => {
  loginForm.value.validate(async (valid) => {
    if (valid) {
      form.type = 0;
      const res = await adminLogin(form);
      setToken(res.data.token);
      user.value = res.data.user;
      user.value.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif' || res.data.user.avatar;
      setUser(user.value);
      await router.push('/home');
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f8ff; /* 浅蓝色背景 */
}

.box-card {
  width: 400px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  padding: 20px;
  //background-color: #409EFF; /* 蓝色背景 */
  color: white;
  border-radius: 10px 10px 0 0;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.login-button {
  width: 100%;
  margin-top: 20px;
  background-color: #409EFF; /* 蓝色背景 */
  border-color: #409EFF;
  color: white;
}

.login-button:hover {
  background-color: #66b1ff; /* 浅蓝色背景 */
  border-color: #66b1ff;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}
</style>
